using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MockSchoolManagement.CustomerMiddlewares;
using MockSchoolManagement.DataRepositories;
using MockSchoolManagement.Infrastructure;

namespace MockSchoolManagement
{
    public class Startup
    {
        private IConfiguration _configuration;

        public Startup(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            //配置数据库
            var connection = _configuration.GetConnectionString("Db");
            services.AddDbContextPool<AppDbContext>(
               options => options.UseSqlServer(connection)
                );
            services.AddIdentity<IdentityUser,IdentityRole>()
                .AddErrorDescriber<CustomIdentityErrorDescriber>()
                .AddEntityFrameworkStores<AppDbContext>();
            services.AddControllersWithViews(a => a.EnableEndpointRouting = false);
            services.AddControllersWithViews(config=>
           {
               var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
               config.Filters.Add(new AuthorizeFilter(policy));

            }).AddXmlSerializerFormatters();
            services.AddScoped<IStudentRepository, StudentRepository>();
            //services.AddScoped<IStudentRepository, MockStudentRepository>();
            //AddXmlSerializerFormatters();
            
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //如果环境是Development serve Developer Exception Page
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //else提供具有应用程序支持的用户友好错误页面联系信息
            else if (env.IsStaging() || env.IsProduction() || env.IsEnvironment("UAT"))
            {
                app.UseExceptionHandler(errorHandlingPath: "/Error");
                app.UseStatusCodePagesWithReExecute("/Error/{0}");
                //app.UseStatusCodePagesWithReExecute("/Error", "?statusCode={0}");
            }
            app.UseStatusCodePagesWithReExecute("/Error/{0}");
            //使用纯静态文件支持的中间件，而不使用带有终端中间件
            app.UseStaticFiles();
            //Identity验证
            app.UseAuthentication();

            app.UseMvcWithDefaultRoute();
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            endpoints.MapControllerRoute(
                name: "default",
                pattern:"{Controller=Home}/{action=index}"
                )
            );
            //app.Run(async (context) =>
            //{
            //    await context.Response.WriteAsync("Hello World!");
            //});
        }
    }
}